//
//  DianpuViewController.swift
//  联付商圈
//
//  Created by zhangqi on 2017/8/9.
//  Copyright © 2017年 lianfu. All rights reserved.
//

import UIKit
import Alamofire
import Kingfisher
import MapKit
import CoreLocation


class DianpuViewController: BaseViewController {
    
    
    @IBAction func dis(_ sender: UIBarButtonItem) {
        self.clearAllNotice()
        //self.dismiss(animated: true, completion: nil)
        self.navigationController?.popViewController(animated: true)
    }
    @IBOutlet weak var titleImg: UIImageView!
    
    @IBOutlet weak var neirongView: UIView!
    
    @IBOutlet weak var titleView: UIView!
    
    @IBOutlet weak var jieshaoView: UIView!
    
    @IBOutlet weak var mapbtnView: UIView!
    
    @IBOutlet weak var mapView: MKMapView!
    
    
   
    
    
    @IBOutlet weak var jiaocheBtn: UIButton!
    @IBAction func jiaocheBtn(_ sender: UIButton) {
    }
    
    enum UpOrDownScroller {
        case Up
        case Down
    }
    
    let ascrollView = UIScrollView()
    
    var dpzj:Double = 0.0
    var numArray = [Int]()
    var idArray = [Int]()
    var nameArray = [String]()
    var jiageArray = [Double]()
    var imgArray = [String]()
    
    var cellcount = 0
    var dianpiuid = dpid
    var cellinfor = ""
    var ScrollState: UpOrDownScroller?
    let locationManager = CLLocationManager()
    lazy var offSetFornex: CGFloat = 0
    var dianjizuobiao:Int = 0
    var rightScrollReason: Bool!
    var isTarget = true
    var targetRect = CGRect()
    
    var panduan = false
    var countjilu = 0
    var indexrow = 0
    var titleArr = [[String:Any]]()
    var rightArr = [[String:Any]]()
    var shopArr = NSDictionary()
    
    @IBOutlet weak var zongjiaLabel: UILabel!
    
    @IBOutlet weak var shangdianImage: UIImageView!
    
    @IBOutlet weak var shoucangBtn: UIButton!
    @IBAction func shoucangBtn(_ sender: UIButton) {
        
    }
    
    
    @IBOutlet weak var dianhuaBtn: UIButton!
    @IBAction func dianhuaBtn(_ sender: UIButton) {
        
    }
    
    @IBOutlet weak var sahngdianmingLabel: UILabel!
    
    @IBOutlet weak var yunfeiLabel: UILabel!
    
    @IBOutlet weak var gonggaoLabel: UILabel!
    
    @IBOutlet weak var dizhiLabel: UILabel!
    
    
    @IBOutlet weak var rightTableView: UITableView!
    
    
   // @IBOutlet weak var totalScrollView: UIScrollView!
    
    
    @IBAction func maidanBtn(_ sender: UIButton) {
        
        
        let x = UserDefaults.standard.object(forKey: "userInfo") as? NSDictionary
        if x == nil {
            self.noticeInfo("未登录", autoClear: true, autoClearTime: 1)
        } else if x != nil && dpzj == 0.0 {
            self.noticeInfo("未选择商品", autoClear: true, autoClearTime: 1)
        } else if x != nil && dpzj > 0.0 {
        let sb = UIStoryboard(name: "Main", bundle:nil)
        let secondViewController = sb.instantiateViewController(withIdentifier: "DingdanViewController") as! DingdanViewController
        self.navigationController?.pushViewController(secondViewController, animated: true)
       }
    }
    
    
    
    
    
    
    
    
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        neirongView.isHidden = true
        titleView.isHidden = true
        rightTableView.isHidden = true
        jieshaoView.isHidden = true
        mapbtnView.isHidden = true
        mapView.isHidden = true
        jiaocheBtn.isHidden = true
        titleImg.isHidden = true
        ascrollView.delegate = self
        
        self.view.addSubview(ascrollView)
        ascrollView.frame = CGRect(x: 0, y: 0, width: Int(UIScreen.main.bounds.width), height: Int(UIScreen.main.bounds.height - 42))
        ascrollView.alwaysBounceVertical = true
        ascrollView.alwaysBounceHorizontal = true
        ascrollView.contentSize = CGSize(width: Int(UIScreen.main.bounds.width), height: 889)
        ascrollView.addSubview(neirongView)
        getshopinfor()
        shangdianming = ""
        zonghjia = 0.0
        param = [String:String]()
        //self.navigationController?.navigationBar.tintColor = UIColor.white
        
        //self.pleaseWait()
        rightTableView.tag = 1002
        //shoucangBtn.isHidden = true
        //totalScrollView.isScrollEnabled = false
        
        rightTableView.tableFooterView = UIView(frame: CGRect.zero)
        self.rightTableView.showsVerticalScrollIndicator = false
        ascrollView.showsVerticalScrollIndicator = false

        zongjiaLabel.text = "价格总计\(0.0)元"
        
        
    }
    
    func xianding(){
        neirongView.frame = CGRect(x: 0, y: 0, width: Int(UIScreen.main.bounds.width), height: 569 + 80*cellcount)
        titleView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 175)
        rightTableView.frame = CGRect(x: 0, y: 175, width: Int(UIScreen.main.bounds.width), height: 80*cellcount + 44)
        jieshaoView.frame = CGRect(x: 0, y: 175 + 44 + 80*cellcount, width: Int(UIScreen.main.bounds.width), height: 175)
        mapbtnView.frame = CGRect(x: 0, y: 394 + 80*cellcount, width: Int(UIScreen.main.bounds.width), height: 175)
        mapView.frame = CGRect(x: 0, y: 0, width: Int(UIScreen.main.bounds.width), height: 175)
        jiaocheBtn.frame = CGRect(x: UIScreen.main.bounds.width/2 - 23, y: 175/2 - 23, width: 46, height: 46)
        titleImg.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 175)
        neirongView.isHidden = false
        titleView.isHidden = false
        rightTableView.isHidden = false
        jieshaoView.isHidden = false
        mapbtnView.isHidden = false
        mapView.isHidden = false
        jiaocheBtn.isHidden = false
        titleImg.isHidden = false
    }
    
    override func viewWillAppear(_ animated: Bool) {
        //self.navigationController?.setNavigationBarHidden(true, animated: true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func getshopinfor(){
        
        let manager = Alamofire.SessionManager.default
        manager.session.configuration.timeoutIntervalForRequest = 45
        let parameters = ["shop_id":"\(dianpiuid)"]
        let urlString = "https://www.beidikeji.com/life/public/jiekou2/products?"
            manager.request(urlString,method:.post,parameters: parameters).responseJSON {Request in
            switch Request.result {
            case .success:
                let json = JSON(data: Request.data!)
                
                //a是分类
                let a = json["a"].arrayObject
                let c = json["shop"][0].dictionaryObject
                self.rightArr = a as! [[String : Any]]
                self.cellcount = self.rightArr.count
                self.xianding()
                self.shopArr = c! as NSDictionary
                
                let latit = self.shopArr["shoplat"] as? String
                let longit = self.shopArr["shoplng"] as? String
                self.sahngdianmingLabel.text = self.shopArr["shopname"] as? String
                shangdianming = (self.shopArr["shopname"] as? String)!
                self.yunfeiLabel.text = self.shopArr["shoplabel"] as? String
                self.gonggaoLabel.text = self.shopArr["shopgonggao"] as? String
                let one = self.shopArr["address1"] as? String
                let two = self.shopArr["address2"] as? String
                self.dizhiLabel.text = one! + two!
                self.dianhuaBtn.setTitle(self.shopArr["app_tel"] as? String, for: UIControlState.highlighted)
                 //self.navigationItem.title = shangdianming
                let imageString = self.shopArr["shopimg"] as? String
                
                
                for z in 0 ..< self.rightArr.count {
                    self.numArray.append(0)
                    self.idArray.append(self.rightArr[z]["id"]! as! Int)
                    self.nameArray.append(self.rightArr[z]["product_name"] as! String)
                    self.jiageArray.append(self.rightArr[z]["nowprice"] as! Double)
                    self.imgArray.append(self.rightArr[z]["image_url"] as! String)
                   }
                let currentLocationSpan:MKCoordinateSpan = MKCoordinateSpanMake(0.05, 0.05)
                let center:CLLocation = CLLocation(latitude: Double(latit!)!, longitude: Double(longit!)!)
                let currentRegion:MKCoordinateRegion = MKCoordinateRegion(center: center.coordinate, span: currentLocationSpan)
                self.mapView.setRegion(currentRegion, animated: true)
                self.mapView.isScrollEnabled = false
                self.mapView.isZoomEnabled = false
                if imageString != nil {
                let url = URL(string:imageString!)
                self.shangdianImage.kf.setImage(with: url, placeholder: nil, options: nil, progressBlock: nil, completionHandler: { (image, error, type, urls) in
                    if error == nil && url == urls {
                    }})
                    
                } else {
                }
                DispatchQueue.main.async(execute: {
                    self.reload()
                })
            case .failure:
                self.noticeInfo("未知错误", autoClear: true, autoClearTime: 1)
            }
        }
        
    }
    
    
    
  
    
    func reload(){
        rightTableView.reloadData()
        self.clearAllNotice()
    }
    

    
    func add(sender: UIButton){
        let x = sender.tag
        numArray[x] += 1
        tongji()
        reload()
    }
    

    func less(sender: UIButton){
        let x = sender.tag
        if numArray[x] > 0 {
            numArray[x] -= 1
        } else if numArray[x] <= 0 {
            numArray[x] = 0
        }
        tongji()
        reload()
    }
    
    func tongji(){
        var tt = [Double]()
        for x in 0 ..< numArray.count {
            let q = Double(numArray[x])
            let w = jiageArray[x]
            tt.append(q*w)
        }
        numArr = numArray
        idArr = idArray
        nameArr = nameArray
        jiageArr = jiageArray
        imgArr = imgArray
        dpzj = tt.reduce(0,{$0 + $1})
        zongjiaLabel.text = "价格总计" + "\(dpzj)" + "元"
    }
    
    

}

extension DianpuViewController:UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate {
    
    
    
    // 设置分区下面的行数 3
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return nameArray.count
        }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell1 = tableView.dequeueReusableCell(withIdentifier: "RightTableViewCell", for: indexPath) as! RightTableViewCell
            cell1.addBtn.tag = indexPath.row
            cell1.lessBtn.tag = indexPath.row
            cell1.addBtn.layer.cornerRadius = 12.0
            cell1.lessBtn.layer.cornerRadius = 12.0
            cell1.selectionStyle = UITableViewCellSelectionStyle.none
            cell1.addBtn.addTarget(self, action:#selector(DianpuViewController.add), for: .touchUpInside)
            cell1.lessBtn.addTarget(self, action: #selector(DianpuViewController.less), for: .touchUpInside)
            cell1.commLabel.text = nameArray[indexPath.row]
            cell1.priceLabel.text = "\(numArray[indexPath.row])"
            cell1.jiageLabel.text = "\(jiageArray[indexPath.row])"
            self.setup(cell1: cell1, atIndexPath: indexPath)
            return cell1
    }
    
    
    
    func setup(cell1: RightTableViewCell, atIndexPath indexPath: IndexPath) {
        let  or = imgArray[indexPath.row]
        let url = URL(string:or)
        if cell1.shangpinImage.kf.webURL != url {
            let cellFrame = self.rightTableView.rectForRow(at: indexPath)
            var shouldLoadImage = true
            if self.isTarget && !self.targetRect.intersects(cellFrame) {
                let image = KingfisherManager.shared.cache.retrieveImageInDiskCache(forKey: or, options: nil)
                if image == nil {
                    shouldLoadImage = false
                }
            }
            if shouldLoadImage {
                cell1.shangpinImage.kf.setImage(with: url, placeholder: nil, options: nil, progressBlock: nil, completionHandler: { (image, error, type, urls) in
                    if error == nil && url == urls {
                        //self.tupianBool = true
//                        UIView.animate(withDuration: 0.25, animations: {
//                            cell1.shangpinImage.alpha = 1.0
//                        })
                    }})}
            
        }}
    
    
    // 5
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
    


    
   func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
    rightScrollReason = false
    }
    
    
    
    
    
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        self.targetRect = CGRect(x: targetContentOffset.pointee.x, y: targetContentOffset.pointee.y, width: scrollView.frame.size.width, height: scrollView.frame.size.height)
        self.isTarget = true
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        self.isTarget = false
        self.loadImageForVisibleCells()
    }
    
    func loadImageForVisibleCells() {
        let visibleCells = self.rightTableView.visibleCells
        for cell in visibleCells {
            self.setup(cell1: cell as! RightTableViewCell, atIndexPath: self.rightTableView.indexPath(for: cell)!)
        }
    }

    
    
    
    
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.ascrollView.contentOffset.x = 0
    }
    
}

